<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级文本处理工具 - 敏感词小组管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        :root {
            --primary: #2563eb;
            --primary-light: #3b82f6;
            --primary-dark: #1d4ed8;
            --secondary: #64748b;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --light-bg: #f8fafc;
            --dark-bg: #0f172a;
            --card-bg: #ffffff;
            --dark-card-bg: #1e293b;
            --text-primary: #0f172a;
            --text-secondary: #64748b;
            --dark-text-primary: #f8fafc;
            --dark-text-secondary: #94a3b8;
            --border-color: #e2e8f0;
            --dark-border-color: #334155;
            --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            --dark-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3);
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: var(--light-bg);
            color: var(--text-primary);
            transition: var(--transition);
            line-height: 1.6;
            padding: 20px;
        }

        body.dark-mode {
            background-color: var(--dark-bg);
            color: var(--dark-text-primary);
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        body.dark-mode header {
            border-bottom-color: var(--dark-border-color);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .current-group {
            background-color: rgba(37, 99, 235, 0.1);
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            border: 1px solid var(--primary);
        }

        body.dark-mode .current-group {
            background-color: rgba(37, 99, 235, 0.2);
        }

        .theme-toggle {
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            font-size: 20px;
            transition: var(--transition);
        }

        body.dark-mode .theme-toggle {
            color: var(--dark-text-secondary);
        }

        .theme-toggle:hover {
            color: var(--primary);
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            margin-bottom: 30px;
        }

        @media (max-width: 1024px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background-color: var(--card-bg);
            border-radius: 8px;
            box-shadow: var(--shadow);
            padding: 20px;
            transition: var(--transition);
        }

        body.dark-mode .card {
            background-color: var(--dark-card-bg);
            box-shadow: var(--dark-shadow);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        body.dark-mode .card-header {
            border-bottom-color: var(--dark-border-color);
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .card-description {
            font-size: 14px;
            color: var(--text-secondary);
            margin-top: 4px;
        }

        body.dark-mode .card-description {
            color: var(--dark-text-secondary);
        }

        .editor-container {
            position: relative;
        }

        textarea {
            width: 100%;
            min-height: 300px;
            padding: 15px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 14px;
            resize: vertical;
            background-color: var(--card-bg);
            color: var(--text-primary);
            transition: var(--transition);
            line-height: 1.6;
        }

        body.dark-mode textarea {
            background-color: var(--dark-card-bg);
            color: var(--dark-text-primary);
            border-color: var(--dark-border-color);
        }

        textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--primary-dark);
        }

        .btn-secondary {
            background-color: var(--border-color);
            color: var(--text-primary);
        }

        body.dark-mode .btn-secondary {
            background-color: var(--dark-border-color);
            color: var(--dark-text-primary);
        }

        .btn-secondary:hover {
            background-color: var(--text-secondary);
            color: white;
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-success:hover {
            background-color: #059669;
        }

        .btn-warning {
            background-color: var(--warning);
            color: white;
        }

        .btn-warning:hover {
            background-color: #d97706;
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn-danger:hover {
            background-color: #dc2626;
        }

        .btn-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }

        .history-section {
            margin-top: 20px;
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .history-title {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .history-controls {
            display: flex;
            gap: 8px;
        }

        .history-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 5px;
            transition: var(--transition);
        }

        body.dark-mode .history-list {
            border-color: var(--dark-border-color);
        }

        .history-item {
            padding: 10px;
            margin-bottom: 5px;
            border-radius: 4px;
            cursor: pointer;
            transition: var(--transition);
            font-size: 14px;
        }

        .history-item:hover {
            background-color: rgba(37, 99, 235, 0.1);
        }

        body.dark-mode .history-item:hover {
            background-color: rgba(37, 99, 235, 0.2);
        }

        .history-item.active {
            background-color: rgba(37, 99, 235, 0.2);
            border-left: 3px solid var(--primary);
        }

        .history-meta {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
            font-size: 12px;
            color: var(--text-secondary);
        }

        body.dark-mode .history-meta {
            color: var(--dark-text-secondary);
        }

        .history-preview {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .history-count {
            font-size: 12px;
            color: var(--text-secondary);
            margin-left: 8px;
        }

        body.dark-mode .history-count {
            color: var(--dark-text-secondary);
        }

        .status-bar {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            font-size: 13px;
            color: var(--text-secondary);
        }

        body.dark-mode .status-bar {
            color: var(--dark-text-secondary);
        }

        .action-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .toggle-container {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-left: auto;
        }

        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--border-color);
            transition: .4s;
            border-radius: 34px;
        }

        body.dark-mode .toggle-slider {
            background-color: var(--dark-border-color);
        }

        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .toggle-slider {
            background-color: var(--primary);
        }

        input:checked + .toggle-slider:before {
            transform: translateX(20px);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.show {
            display: flex;
        }

        .modal-content {
            background-color: var(--card-bg);
            border-radius: 8px;
            width: 90%;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: var(--shadow);
        }

        body.dark-mode .modal-content {
            background-color: var(--dark-card-bg);
            box-shadow: var(--dark-shadow);
        }

        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        body.dark-mode .modal-header {
            border-bottom-color: var(--dark-border-color);
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: var(--text-secondary);
        }

        body.dark-mode .modal-close {
            color: var(--dark-text-secondary);
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        body.dark-mode .modal-footer {
            border-top-color: var(--dark-border-color);
        }

        .save-indicator {
            position: absolute;
            bottom: 10px;
            right: 10px;
            font-size: 12px;
            color: var(--success);
            opacity: 0;
            transition: opacity 0.3s;
        }

        .save-indicator.show {
            opacity: 1;
        }

        .settings-group {
            margin-bottom: 15px;
        }

        .settings-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background-color: var(--card-bg);
            color: var(--text-primary);
            font-size: 14px;
        }

        body.dark-mode .form-control {
            background-color: var(--dark-card-bg);
            color: var(--dark-text-primary);
            border-color: var(--dark-border-color);
        }

        .rule-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
            padding: 8px;
            background-color: rgba(0, 0, 0, 0.03);
            border-radius: 4px;
        }

        body.dark-mode .rule-item {
            background-color: rgba(255, 255, 255, 0.03);
        }

        .rule-input {
            flex: 1;
            padding: 6px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background-color: var(--card-bg);
            color: var(--text-primary);
        }

        body.dark-mode .rule-input {
            background-color: var(--dark-card-bg);
            color: var(--dark-text-primary);
            border-color: var(--dark-border-color);
        }

        .remove-rule-btn {
            background-color: var(--danger);
            color: white;
            border: none;
            border-radius: 4px;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
        }

        .group-list {
            border: 1px solid var(--border-color);
            border-radius: 6px;
            margin-bottom: 15px;
            max-height: 200px;
            overflow-y: auto;
        }

        body.dark-mode .group-list {
            border-color: var(--dark-border-color);
        }

        .group-item {
            padding: 10px 15px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }

        body.dark-mode .group-item {
            border-bottom-color: var(--dark-border-color);
        }

        .group-item:last-child {
            border-bottom: none;
        }

        .group-item:hover {
            background-color: rgba(37, 99, 235, 0.1);
        }

        .group-item.active {
            background-color: rgba(37, 99, 235, 0.2);
        }

        .group-actions {
            display: flex;
            gap: 5px;
        }

        .group-action-btn {
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            width: 24px;
            height: 24px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .group-action-btn:hover {
            background-color: rgba(0, 0, 0, 0.1);
            color: var(--primary);
        }

        .import-export-group {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .import-container {
            position: relative;
            flex: 1;
        }

        .import-input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .import-format-hint {
            font-size: 12px;
            color: var(--text-secondary);
            margin-top: 5px;
            font-style: italic;
        }

        body.dark-mode .import-format-hint {
            color: var(--dark-text-secondary);
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="logo">
                <i class="fa fa-file-text-o" aria-hidden="true"></i>
                <h1>高级文本处理工具</h1>
            </div>
            <div class="current-group" id="currentGroupIndicator">
                <i class="fa fa-shield" aria-hidden="true"></i>
                <span>当前敏感词小组：<strong id="currentGroupName">默认小组</strong></span>
            </div>
            <div class="toggle-container">
                <span>实时处理</span>
                <label class="toggle-switch">
                    <input type="checkbox" id="realTimeToggle">
                    <span class="toggle-slider"></span>
                </label>
            </div>
            <button class="theme-toggle" id="themeToggle" title="切换主题">
                <i class="fa fa-moon-o" aria-hidden="true"></i>
            </button>
        </header>

        <div class="action-bar">
            <button class="btn btn-secondary" id="importBtn">
                <i class="fa fa-upload" aria-hidden="true"></i> 导入文本
            </button>
            <input type="file" id="fileInput" accept=".txt" style="display: none;">
            <button class="btn btn-secondary" id="exportBtn">
                <i class="fa fa-download" aria-hidden="true"></i> 导出结果
            </button>
            <button class="btn btn-warning" id="loadSampleBtn">
                <i class="fa fa-file-text-o" aria-hidden="true"></i> 加载示例
            </button>
            <button class="btn btn-secondary" id="groupsBtn">
                <i class="fa fa-tags" aria-hidden="true"></i> 敏感词小组管理
            </button>
            <button class="btn btn-danger" id="clearAllBtn">
                <i class="fa fa-trash" aria-hidden="true"></i> 清空所有
            </button>
        </div>

        <div class="main-content">
            <!-- 主编辑区 -->
            <div class="card">
                <div class="card-header">
                    <div>
                        <div class="card-title">
                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i> 主编辑区
                        </div>
                        <div class="card-description">输入原始文本，所有修改将自动保存历史记录（最多20条）</div>
                    </div>
                </div>
                <div class="editor-container">
                    <textarea id="mainEditor" placeholder="请输入或粘贴文本内容..."></textarea>
                    <div class="save-indicator" id="mainSaveIndicator">
                        <i class="fa fa-check" aria-hidden="true"></i> 已保存
                    </div>
                </div>
                <div class="status-bar">
                    <div id="mainStats">字数: 0 | 行数: 0</div>
                    <div id="mainHistoryStatus">历史记录: 0/20</div>
                </div>
                <div class="btn-group">
                    <button class="btn btn-primary" id="processBtn">
                        <i class="fa fa-cogs" aria-hidden="true"></i> 处理文本
                    </button>
                    <button class="btn btn-secondary" id="showMainHistoryBtn">
                        <i class="fa fa-history" aria-hidden="true"></i> 查看历史记录
                    </button>
                </div>

                <!-- 主编辑区历史记录 -->
                <div class="history-section">
                    <div class="history-header">
                        <div class="history-title">
                            <i class="fa fa-clock-o" aria-hidden="true"></i> 最近编辑
                        </div>
                        <div class="history-controls">
                            <button class="btn btn-secondary btn-sm" id="clearMainHistoryBtn">
                                <i class="fa fa-trash-o" aria-hidden="true"></i> 清空
                            </button>
                        </div>
                    </div>
                    <div class="history-list" id="mainHistoryList">
                        <div class="history-item empty-state">暂无编辑记录</div>
                    </div>
                </div>
            </div>

            <!-- 二次编辑区 -->
            <div class="card">
                <div class="card-header">
                    <div>
                        <div class="card-title">
                            <i class="fa fa-edit" aria-hidden="true"></i> 二次编辑区
                        </div>
                        <div class="card-description">处理后的文本可在此进一步编辑，自动保存历史记录（最多20条）</div>
                    </div>
                </div>
                <div class="editor-container">
                    <textarea id="secondaryEditor" placeholder="处理后的文本将显示在这里，可继续编辑..."></textarea>
                    <div class="save-indicator" id="secondarySaveIndicator">
                        <i class="fa fa-check" aria-hidden="true"></i> 已保存
                    </div>
                </div>
                <div class="status-bar">
                    <div id="secondaryStats">字数: 0 | 行数: 0</div>
                    <div id="secondaryHistoryStatus">历史记录: 0/20</div>
                </div>
                <div class="btn-group">
                    <button class="btn btn-success" id="copyBtn">
                        <i class="fa fa-copy" aria-hidden="true"></i> 复制结果
                    </button>
                    <button class="btn btn-secondary" id="showSecondaryHistoryBtn">
                        <i class="fa fa-history" aria-hidden="true"></i> 查看历史记录
                    </button>
                </div>

                <!-- 二次编辑区历史记录 -->
                <div class="history-section">
                    <div class="history-header">
                        <div class="history-title">
                            <i class="fa fa-clock-o" aria-hidden="true"></i> 最近编辑
                        </div>
                        <div class="history-controls">
                            <button class="btn btn-secondary btn-sm" id="clearSecondaryHistoryBtn">
                                <i class="fa fa-trash-o" aria-hidden="true"></i> 清空
                            </button>
                        </div>
                    </div>
                    <div class="history-list" id="secondaryHistoryList">
                        <div class="history-item empty-state">暂无编辑记录</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 历史记录详情模态框 -->
    <div class="modal" id="historyModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="modalTitle">历史记录详情</h3>
                <button class="modal-close" id="modalClose">&times;</button>
            </div>
            <div class="modal-body">
                <div class="history-detail">
                    <div class="history-detail-header" id="historyDetailHeader">版本: 1 (2023-10-04 12:00:00)</div>
                    <div class="history-content" id="historyContent"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="modalCancelBtn">关闭</button>
                <button class="btn btn-primary" id="restoreBtn">恢复此版本</button>
            </div>
        </div>
    </div>

    <!-- 敏感词小组管理模态框 -->
    <div class="modal" id="groupsModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">敏感词小组管理</h3>
                <button class="modal-close" id="groupsClose">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="settings-label" for="groupName">小组名称</label>
                    <input type="text" id="groupName" class="form-control" placeholder="输入敏感词小组名称">
                </div>

                <div class="settings-label">敏感词小组列表</div>
                <div class="group-list" id="groupList">
                    <!-- 小组列表将通过JS动态生成 -->
                </div>

                <div class="import-export-group">
                    <div class="import-container">
                        <button class="btn btn-secondary" id="importGroupBtn">
                            <i class="fa fa-upload" aria-hidden="true"></i> 导入小组
                        </button>
                        <input type="file" id="groupFileInput" accept=".json,.txt" class="import-input">
                        <div class="import-format-hint">支持JSON和TXT格式（TXT每行格式: 敏感词=替换词）</div>
                    </div>
                    <button class="btn btn-secondary" id="exportGroupBtn">
                        <i class="fa fa-download" aria-hidden="true"></i> 导出当前小组
                    </button>
                    <button class="btn btn-success" id="addNewGroupBtn">
                        <i class="fa fa-plus" aria-hidden="true"></i> 新建小组
                    </button>
                </div>

                <div class="settings-label">当前小组敏感词规则</div>
                <div class="settings-group" id="replacementRules">
                    <!-- 规则将通过JS动态生成 -->
                </div>
                <button class="btn btn-secondary" id="addRuleBtn">
                    <i class="fa fa-plus" aria-hidden="true"></i> 添加替换规则
                </button>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="groupsCancelBtn">关闭</button>
                <button class="btn btn-primary" id="saveGroupBtn">保存当前小组</button>
            </div>
        </div>
    </div>

    <!-- 首次使用说明弹窗 -->
    <div class="modal" id="guideModal" style="z-index: 1001;">
        <div class="modal-content" style="max-width: 900px;">
            <div class="modal-header">
                <h3 class="modal-title"><i class="fa fa-lightbulb-o" aria-hidden="true"></i> 欢迎使用高级文本处理工具</h3>
                <button class="modal-close" id="guideClose">&times;</button>
            </div>
            <div class="modal-body" style="font-size: 14px; line-height: 1.8;">
                <div style="margin-bottom: 15px;">
                    <h4 style="margin-bottom: 8px; color: var(--primary);"><i class="fa fa-star" aria-hidden="true"></i> 核心功能介绍</h4>
                    <ul style="padding-left: 20px; margin-bottom: 10px;">
                        <li><strong>敏感词小组管理</strong>：创建多个敏感词规则组（如“工作文档组”“社交文本组”），可随时切换，针对不同场景精准处理</li>
                        <li><strong>双编辑区协作</strong>：左侧“主编辑区”输入原始文本，右侧“二次编辑区”显示处理结果，支持进一步修改</li>
                        <li><strong>自动历史记录</strong>：两个编辑区各保留20条历史版本，可随时查看、恢复之前的编辑内容</li>
                        <li><strong>实时/手动处理</strong>：开启“实时处理”后，主编辑区输入时自动同步处理结果；关闭则需点击“处理文本”按钮</li>
                    </ul>
                </div>
                <div style="margin-bottom: 15px;">
                    <h4 style="margin-bottom: 8px; color: var(--primary);"><i class="fa fa-list-ol" aria-hidden="true"></i> 快速操作步骤</h4>
                    <ol style="padding-left: 20px; margin-bottom: 10px;">
                        <li>点击顶部<strong>“敏感词小组管理”</strong>，创建/导入专属敏感词规则（默认提供“默认小组”，含基础敏感词）</li>
                        <li>在左侧“主编辑区”输入/粘贴文本（支持导入TXT文件）</li>
                        <li>开启“实时处理”自动生成结果，或点击<strong>“处理文本”</strong>手动触发处理</li>
                        <li>在右侧“二次编辑区”调整结果，完成后点击<strong>“复制结果”</strong>或“导出结果”保存</li>
                    </ol>
                </div>
                <div>
                    <h4 style="margin-bottom: 8px; color: var(--primary);"><i class="fa fa-info-circle" aria-hidden="true"></i> 温馨提示</h4>
                    <ul style="padding-left: 20px;">
                        <li>敏感词小组支持<strong>导入/导出</strong>（JSON和TXT格式），可备份或共享规则</li>
                        <li>点击顶部“当前敏感词小组”可快速确认当前使用的规则组</li>
                        <li>右上角可切换“暗黑模式”，适应不同使用环境</li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <label style="display: flex; align-items: center; margin-right: 20px; cursor: pointer;">
                    <input type="checkbox" id="dontShowAgain" style="margin-right: 8px;">
                    <span>不再显示此说明</span>
                </label>
                <button class="btn btn-primary" id="guideConfirmBtn">
                    <i class="fa fa-check" aria-hidden="true"></i> 我知道了
                </button>
            </div>
        </div>
    </div>

    <script>
        // 敏感词小组管理类
        class KeywordGroupManager {
            constructor() {
                this.groups = this.loadGroups();
                this.currentGroupId = this.loadCurrentGroupId();
            }

            // 从本地存储加载敏感词小组
            loadGroups() {
                const stored = localStorage.getItem('keywordGroups');
                if (stored) {
                    return JSON.parse(stored);
                }
                
                // 默认小组 - 始终保留，不可删除
                return [
                    {
                        id: 'default',
                        name: '默认小组',
                        rules: {
                            "私处": "S处",
                            "胃": "胄",
                            "药": "薬",
                            "炎": "焱",
                            "命": "m",
                            "毒": "du",
                            "死": "s",
                            "病": "疒",
                            "医": "y",
                            "救": "慦",
                            "谎": "h",   
                            "治": "滞",
                            "安全": "桉荃",
                            "便宜": "便易",
                            "必好": "",
                            "不要钱": "",
                            "阎": "y",
                            "负责": "",
                            "找我": "",
                            "担保": "",
                            "保证": "bz",
                            "辈": "bei",
                            "滚": "gun",
                            "妈": "m",
                            "癌": "ai",
                            "复": "fu",
                            "血": "皿",
                            "臭": "嗅",
                            "分泌物": "FMW",
                            "溃疡": "KY",
                            "她": "它",
                            "他": "它",
                            "挂号": "G号"
                        }
                    }
                ];
            }

            // 加载当前选中的小组ID
            loadCurrentGroupId() {
                return localStorage.getItem('currentKeywordGroupId') || 'default';
            }

            // 保存小组到本地存储
            saveGroups() {
                localStorage.setItem('keywordGroups', JSON.stringify(this.groups));
            }

            // 保存当前选中的小组ID
            saveCurrentGroupId() {
                localStorage.setItem('currentKeywordGroupId', this.currentGroupId);
            }

            // 获取所有小组
            getAllGroups() {
                return [...this.groups];
            }

            // 获取当前小组
            getCurrentGroup() {
                return this.groups.find(group => group.id === this.currentGroupId) || this.groups[0];
            }

            // 获取指定ID的小组
            getGroupById(id) {
                return this.groups.find(group => group.id === id);
            }

            // 切换当前小组
            switchGroup(id) {
                const group = this.getGroupById(id);
                if (group) {
                    this.currentGroupId = id;
                    this.saveCurrentGroupId();
                    return true;
                }
                return false;
            }

            // 添加新小组 - 确保不会替换现有小组
            addGroup(name, rules = {}) {
                if (!name.trim()) return false;
                
                // 检查是否已有同名小组
                const nameExists = this.groups.some(group => 
                    group.name.toLowerCase() === name.trim().toLowerCase() && group.id !== 'default'
                );
                
                if (nameExists) {
                    alert('已存在同名小组，请使用其他名称');
                    return false;
                }
                
                const id = 'group_' + Date.now();
                this.groups.push({ id, name: name.trim(), rules });
                this.saveGroups();
                return id;
            }

            // 更新小组
            updateGroup(id, data) {
                // 确保不能通过更新方式替换默认小组
                if (id === 'default' && data.name && data.name.toLowerCase() !== '默认小组'.toLowerCase()) {
                    alert('默认小组名称不可更改');
                    return false;
                }
                
                const index = this.groups.findIndex(group => group.id === id);
                if (index !== -1) {
                    this.groups[index] = { ...this.groups[index], ...data };
                    this.saveGroups();
                    return true;
                }
                return false;
            }

            // 删除小组 - 保留默认小组
            deleteGroup(id) {
                // 不能删除默认小组
                if (id === 'default') {
                    alert('默认小组不可删除');
                    return false;
                }
                
                const index = this.groups.findIndex(group => group.id === id);
                if (index !== -1) {
                    this.groups.splice(index, 1);
                    
                    // 如果删除的是当前小组，切换到默认小组
                    if (id === this.currentGroupId) {
                        this.currentGroupId = 'default';
                        this.saveCurrentGroupId();
                    }
                    
                    this.saveGroups();
                    return true;
                }
                return false;
            }

            // 导入小组 - 支持JSON和TXT格式
            importGroup(fileData, fileType) {
                try {
                    let groupData;
                    
                    // 处理TXT格式
                    if (fileType === 'txt') {
                        const lines = fileData.split('\n');
                        const rules = {};
                        
                        lines.forEach((line, index) => {
                            const trimmedLine = line.trim();
                            if (trimmedLine) {
                                const equalsIndex = trimmedLine.indexOf('=');
                                if (equalsIndex > 0) {
                                    const keyword = trimmedLine.substring(0, equalsIndex).trim();
                                    const replacement = trimmedLine.substring(equalsIndex + 1).trim();
                                    if (keyword) {
                                        rules[keyword] = replacement;
                                    }
                                } else {
                                    console.warn(`TXT格式错误，第${index + 1}行未找到"="分隔符: ${trimmedLine}`);
                                }
                            }
                        });
                        
                        groupData = {
                            name: `导入的TXT规则_${new Date().getTime().toString().slice(-4)}`,
                            rules: rules
                        };
                    } 
                    // 处理JSON格式
                    else if (fileType === 'json') {
                        groupData = JSON.parse(fileData);
                        // 验证JSON格式
                        if (typeof groupData !== 'object' || !groupData.name || typeof groupData.rules !== 'object') {
                            throw new Error('JSON格式不正确，需要包含name和rules属性');
                        }
                    }
                    // 不支持的格式
                    else {
                        throw new Error('不支持的文件格式');
                    }
                    
                    // 检查是否已有同名小组
                    const nameExists = this.groups.some(group => 
                        group.name.toLowerCase() === groupData.name.toLowerCase()
                    );
                    
                    let newGroupName = groupData.name;
                    let counter = 1;
                    
                    // 如果名称已存在，添加序号
                    while (nameExists) {
                        newGroupName = `${groupData.name}_${counter}`;
                        const exists = this.groups.some(group => 
                            group.name.toLowerCase() === newGroupName.toLowerCase()
                        );
                        if (!exists) break;
                        counter++;
                    }
                    
                    const id = 'group_' + Date.now();
                    this.groups.push({
                        id,
                        name: newGroupName,
                        rules: groupData.rules || {}
                    });
                    this.saveGroups();
                    return id;
                } catch (e) {
                    console.error('导入小组失败:', e);
                    alert(`导入失败: ${e.message}`);
                    return null;
                }
            }

            // 导出当前小组
            exportCurrentGroup(format = 'json') {
                const group = this.getCurrentGroup();
                if (!group) {
                    return null;
                }
                
                // 导出为JSON
                if (format === 'json') {
                    return {
                        name: group.name,
                        rules: group.rules
                    };
                } 
                // 导出为TXT
                else if (format === 'txt') {
                    let content = '';
                    Object.keys(group.rules).forEach(keyword => {
                        content += `${keyword}=${group.rules[keyword]}\n`;
                    });
                    return content;
                }
                
                return null;
            }
        }

        // 文本替换器类 - 实现敏感词替换功能，包含改进的小数处理逻辑
        class TextReplacer {
            constructor(text, rules = {}) {
                this.original_text = text;
                this.processed_text = text;
                this.replace_rules = rules;
                // 用于存储临时标记和对应的值
                this.decimalMarkers = new Map();
                // 用于生成字母后缀的计数器
                this.markerIndex = 0;
            }

            // 生成字母后缀 (A, B, C, ..., Z, AA, AB, ...)
            generateLetterSuffix() {
                let suffix = '';
                let index = this.markerIndex;
                
                while (true) {
                    // 计算当前字符：0->A, 1->B, ..., 25->Z
                    const charCode = (index % 26) + 65;
                    suffix = String.fromCharCode(charCode) + suffix;
                    index = Math.floor(index / 26) - 1;
                    
                    if (index < 0) break;
                }
                
                this.markerIndex++;
                return suffix;
            }

            // 步骤1: 标记所有带小数点的数字并补全0
            markDecimalNumbers() {
                // 匹配带小数点的数字，包括：
                // - 正数：123.45, .67 → 补全为123.45, 0.67
                // - 负数：-123.45, -.67 → 补全为-123.45, -0.67
                const decimalRegex = /-?\d*\.\d+/g;
                
                this.processed_text = this.processed_text.replace(decimalRegex, (match) => {
                    // 补全小数点前的0
                    let normalized;
                    if (match.startsWith('-.') || match.startsWith('.')) {
                        // 处理：.XX → 0.XX；-.XX → -0.XX
                        normalized = match.startsWith('-') ? `-0${match.slice(1)}` : `0${match}`;
                    } else {
                        normalized = match;
                    }
                    
                    // 生成字母后缀的标记（如DEC_MARKER_A, DEC_MARKER_B）
                    const suffix = this.generateLetterSuffix();
                    const marker = `DEC_MARKER_${suffix}`;
                    
                    // 存储标记与标准化后的值
                    this.decimalMarkers.set(marker, normalized);
                    
                    return marker;
                });
            }

            // 步骤3: 恢复所有被标记的带小数点数字
            restoreDecimalNumbers() {
                this.decimalMarkers.forEach((originalValue, marker) => {
                    const regex = new RegExp(this.escapeRegExp(marker), 'g');
                    this.processed_text = this.processed_text.replace(regex, originalValue);
                });
                this.decimalMarkers.clear();
            }

            // 执行完整替换流程
            process() {
                // 步骤1: 标记并标准化所有小数
                this.markDecimalNumbers();
                
                // 步骤2: 执行正常的文本处理
                this.replace_keywords();
                this.convert_numbers();
                this.replace_punctuation();
                
                // 步骤3: 恢复所有小数
                this.restoreDecimalNumbers();
                
                // 过滤空行
                const lines = this.processed_text.split('\n')
                    .map(line => line.trim())
                    .filter(line => line);
                return lines.join('\n');
            }

            // 敏感词替换
            replace_keywords() {
                const sorted_keys = Object.keys(this.replace_rules).sort((a, b) => b.length - a.length);
                sorted_keys.forEach(keyword => {
                    if (keyword && this.replace_rules[keyword] !== undefined) {
                        const regex = new RegExp(this.escapeRegExp(keyword), 'g');
                        this.processed_text = this.processed_text.replace(regex, this.replace_rules[keyword]);
                    }
                });
            }

            // 整数转换（此时带小数点的数字已被标记保护）
            convert_numbers() {
                // 数字字符映射
                const digitMap = {
                    '0': '零', '1': '一', '2': '二', '3': '三', '4': '四',
                    '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'
                };
                
                // 单位映射
                const unitMap = ['', '十', '百', '千'];
                
                // 转换0-9999的数字
                const convertNumber = (num) => {
                    if (num === 0) return '零';
                    
                    let result = '';
                    let strNum = num.toString();
                    let len = strNum.length;
                    
                    // 处理10-19的特殊情况
                    if (num >= 10 && num < 20) {
                        return '十' + (num > 10 ? digitMap[strNum[1]] : '');
                    }
                    
                    for (let i = 0; i < len; i++) {
                        const digit = parseInt(strNum[i]);
                        if (digit !== 0) {
                            result += digitMap[strNum[i]] + unitMap[len - 1 - i];
                        } else {
                            // 处理零
                            if (result[result.length - 1] !== '零') {
                                result += '零';
                            }
                        }
                    }
                    
                    // 去除末尾的零
                    return result.replace(/零$/, '');
                };
                
                // 匹配整数（此时带小数点的数字已被标记，不会被匹配）
                const numberRegex = /(?:^|[^\d%.])(\d+)(?:$|[^\d]|(?=%))/g;
                
                // 替换函数
                const replaceNumber = (match, numStr) => {
                    const num = parseInt(numStr);
                    const fullMatch = match;
                    
                    // 年份（1900-2100之间）不转换
                    if (num >= 1900 && num <= 2100) {
                        return fullMatch;
                    }
                    
                    // 百分比前面的数字不转换
                    if (fullMatch.endsWith('%') || /\d+%/.test(fullMatch)) {
                        return fullMatch;
                    }
                    
                    // 序号格式（第X）不转换
                    if (/第\d+/.test(fullMatch)) {
                        return fullMatch;
                    }
                    
                    // 超过9999的数字不转换
                    if (num > 9999) {
                        return fullMatch;
                    }
                    
                    // 执行转换
                    const converted = convertNumber(num);
                    return fullMatch.replace(numStr, converted);
                };
                
                // 执行替换
                this.processed_text = this.processed_text.replace(numberRegex, replaceNumber);
            }

            // 标点符号替换
            replace_punctuation() {
                const punctuation_pattern = /[，、。,.;:!?；：！？“”‘’""\'\(\)\[\]\{\}]/g;
                this.processed_text = this.processed_text.replace(punctuation_pattern, '\n');
            }

            // 正则特殊字符转义
            escapeRegExp(str) {
                return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            }
        }

        // 历史记录管理类
        class HistoryManager {
            constructor(storageKey, maxRecords = 20) {
                this.storageKey = storageKey;
                this.maxRecords = maxRecords;
                this.records = this.loadFromStorage();
                this.currentEditor = null;
                this.saveTimeout = null;
            }

            // 从本地存储加载历史记录
            loadFromStorage() {
                const stored = localStorage.getItem(this.storageKey);
                return stored ? JSON.parse(stored) : [];
            }

            // 保存历史记录到本地存储
            saveToStorage() {
                localStorage.setItem(this.storageKey, JSON.stringify(this.records));
            }

            // 添加新的历史记录
            addRecord(content) {
                // 避免添加重复内容
                if (this.records.length > 0 && this.records[0].content === content) {
                    return false;
                }

                const now = new Date();
                const record = {
                    id: Date.now(),
                    timestamp: now.toISOString(),
                    formattedTime: now.toLocaleString(),
                    content: content
                };

                // 添加到历史记录开头
                this.records.unshift(record);

                // 限制历史记录数量
                if (this.records.length > this.maxRecords) {
                    this.records = this.records.slice(0, this.maxRecords);
                }

                // 保存到本地存储
                this.saveToStorage();
                return true;
            }

            // 获取所有历史记录
            getAllRecords() {
                return [...this.records];
            }

            // 获取特定ID的历史记录
            getRecordById(id) {
                return this.records.find(record => record.id === id);
            }

            // 清空历史记录
            clearRecords() {
                this.records = [];
                this.saveToStorage();
            }

            // 设置关联的编辑器
            setEditor(editorElement, saveIndicator) {
                this.currentEditor = editorElement;
                this.saveIndicator = saveIndicator;

                // 监听编辑器内容变化，实现自动保存
                editorElement.addEventListener('input', () => {
                    this.debouncedSave();
                    this.updateStats();
                });
            }

            // 防抖保存
            debouncedSave() {
                clearTimeout(this.saveTimeout);
                this.saveTimeout = setTimeout(() => {
                    const content = this.currentEditor.value;
                    if (content.trim() && this.addRecord(content)) {
                        this.showSaveIndicator();
                        this.renderHistoryList();
                        this.updateHistoryStatus();
                    }
                }, 1000); // 1秒内无变化则保存
            }

            // 显示保存指示器
            showSaveIndicator() {
                if (this.saveIndicator) {
                    this.saveIndicator.classList.add('show');
                    setTimeout(() => {
                        this.saveIndicator.classList.remove('show');
                    }, 2000);
                }
            }

            // 渲染历史记录列表
            renderHistoryList(listElement, emptyStateText = '暂无编辑记录') {
                if (this.records.length === 0) {
                    listElement.innerHTML = `<div class="history-item empty-state">${emptyStateText}</div>`;
                    return;
                }

                listElement.innerHTML = '';
                this.records.forEach((record, index) => {
                    const preview = record.content.length > 50 
                        ? record.content.substring(0, 50) + '...' 
                        : record.content || '空内容';

                    const item = document.createElement('div');
                    item.className = `history-item ${index === 0 ? 'active' : ''}`;
                    item.dataset.id = record.id;
                    item.innerHTML = `
                        <div class="history-meta">
                            <span>版本 ${index + 1}</span>
                            <span>${record.formattedTime}</span>
                        </div>
                        <div class="history-preview">${this.escapeHtml(preview)}</div>
                    `;

                    item.addEventListener('click', () => {
                        // 显示历史记录详情
                        this.showHistoryDetail(record, index + 1);
                    });

                    listElement.appendChild(item);
                });
            }

            // 显示历史记录详情
            showHistoryDetail(record, version) {
                const modal = document.getElementById('historyModal');
                const modalTitle = document.getElementById('modalTitle');
                const historyDetailHeader = document.getElementById('historyDetailHeader');
                const historyContent = document.getElementById('historyContent');
                const restoreBtn = document.getElementById('restoreBtn');

                modalTitle.textContent = `${this.storageKey === 'mainEditorHistory' ? '主编辑区' : '二次编辑区'} 历史记录`;
                historyDetailHeader.textContent = `版本: ${version} (${record.formattedTime})`;
                historyContent.textContent = record.content;

                // 存储要恢复的记录ID和类型
                restoreBtn.dataset.recordId = record.id;
                restoreBtn.dataset.editorType = this.storageKey === 'mainEditorHistory' ? 'main' : 'secondary';

                modal.classList.add('show');
            }

            // 恢复历史记录
            restoreRecord(recordId) {
                const record = this.getRecordById(parseInt(recordId));
                if (record && this.currentEditor) {
                    this.currentEditor.value = record.content;
                    this.debouncedSave(); // 恢复后也作为一个新版本保存
                    this.updateStats();
                    return true;
                }
                return false;
            }

            // 更新统计信息
            updateStats(statsElement) {
                if (!this.currentEditor || !statsElement) return;
                
                const content = this.currentEditor.value;
                const charCount = content.length;
                const lineCount = content.split('\n').length;
                
                statsElement.textContent = `字数: ${charCount} | 行数: ${lineCount}`;
            }

            // 更新历史记录状态
            updateHistoryStatus(statusElement) {
                if (statusElement) {
                    statusElement.textContent = `历史记录: ${this.records.length}/${this.maxRecords}`;
                }
            }

            // HTML转义
            escapeHtml(unsafe) {
                return unsafe
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            }
        }

        // 文本处理工具类
        class TextProcessor {
            constructor() {
                // 初始化敏感词小组管理器
                this.groupManager = new KeywordGroupManager();
                
                // 初始化历史记录管理器（各保留20条）
                this.mainHistory = new HistoryManager('mainEditorHistory', 20);
                this.secondaryHistory = new HistoryManager('secondaryEditorHistory', 20);
                
                // 初始化文本替换器
                this.textReplacer = new TextReplacer('', this.getCurrentRules());
                this.realTimeProcessing = false;
                this.processingTimeout = null;

                // 获取DOM元素
                this.mainEditor = document.getElementById('mainEditor');
                this.secondaryEditor = document.getElementById('secondaryEditor');
                this.mainHistoryList = document.getElementById('mainHistoryList');
                this.secondaryHistoryList = document.getElementById('secondaryHistoryList');
                this.mainStats = document.getElementById('mainStats');
                this.secondaryStats = document.getElementById('secondaryStats');
                this.mainHistoryStatus = document.getElementById('mainHistoryStatus');
                this.secondaryHistoryStatus = document.getElementById('secondaryHistoryStatus');
                this.mainSaveIndicator = document.getElementById('mainSaveIndicator');
                this.secondarySaveIndicator = document.getElementById('secondarySaveIndicator');
                this.replacementRulesContainer = document.getElementById('replacementRules');
                this.realTimeToggle = document.getElementById('realTimeToggle');
                this.currentGroupNameElement = document.getElementById('currentGroupName');
                this.groupNameInput = document.getElementById('groupName');
                this.groupListElement = document.getElementById('groupList');
                
                // 初始化
                this.init();
            }

            // 初始化
            init() {
                // 关联编辑器和历史记录管理器
                this.mainHistory.setEditor(this.mainEditor, this.mainSaveIndicator);
                this.secondaryHistory.setEditor(this.secondaryEditor, this.secondarySaveIndicator);

                // 更新当前小组显示
                this.updateCurrentGroupDisplay();

                // 渲染小组列表和规则
                this.renderGroupList();
                this.renderReplacementRules();

                // 渲染历史记录
                this.mainHistory.renderHistoryList(this.mainHistoryList);
                this.secondaryHistory.renderHistoryList(this.secondaryHistoryList);

                // 更新状态信息
                this.mainHistory.updateStats(this.mainStats);
                this.secondaryHistory.updateStats(this.secondaryStats);
                this.mainHistory.updateHistoryStatus(this.mainHistoryStatus);
                this.secondaryHistory.updateHistoryStatus(this.secondaryHistoryStatus);

                // 绑定事件监听
                this.bindEvents();

                // 检查主题设置
                this.checkTheme();
            }

            // 获取当前小组的规则
            getCurrentRules() {
                const currentGroup = this.groupManager.getCurrentGroup();
                return currentGroup ? currentGroup.rules : {};
            }

            // 更新当前小组显示
            updateCurrentGroupDisplay() {
                const currentGroup = this.groupManager.getCurrentGroup();
                if (currentGroup) {
                    this.currentGroupNameElement.textContent = currentGroup.name;
                }
            }

            // 渲染小组列表
            renderGroupList() {
                const groups = this.groupManager.getAllGroups();
                const currentGroupId = this.groupManager.currentGroupId;
                
                this.groupListElement.innerHTML = '';
                
                groups.forEach(group => {
                    const item = document.createElement('div');
                    item.className = `group-item ${group.id === currentGroupId ? 'active' : ''}`;
                    item.dataset.id = group.id;
                    
                    // 为默认小组添加标识
                    const groupName = group.id === 'default' ? `${group.name} (默认)` : group.name;
                    
                    item.innerHTML = `
                        <span>${groupName}</span>
                        <div class="group-actions">
                            <button class="group-action-btn edit-group" title="编辑小组">
                                <i class="fa fa-pencil" aria-hidden="true"></i>
                            </button>
                            <button class="group-action-btn delete-group ${group.id === 'default' ? 'disabled' : ''}" 
                                    title="${group.id === 'default' ? '默认小组不能删除' : '删除小组'}"
                                    ${group.id === 'default' ? 'disabled' : ''}>
                                <i class="fa fa-trash" aria-hidden="true"></i>
                            </button>
                        </div>
                    `;
                    
                    // 点击小组切换
                    item.addEventListener('click', (e) => {
                        // 避免点击按钮时触发切换
                        if (!e.target.closest('.group-actions')) {
                            this.switchToGroup(group.id);
                        }
                    });
                    
                    // 编辑小组
                    item.querySelector('.edit-group').addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.editGroup(group.id);
                    });
                    
                    // 删除小组
                    const deleteBtn = item.querySelector('.delete-group');
                    if (group.id !== 'default') {
                        deleteBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            this.deleteGroup(group.id);
                        });
                    }
                    
                    this.groupListElement.appendChild(item);
                });
            }

            // 切换到指定小组
            switchToGroup(groupId) {
                if (this.groupManager.switchGroup(groupId)) {
                    this.renderGroupList();
                    this.renderReplacementRules();
                    this.updateCurrentGroupDisplay();
                    
                    // 更新替换器规则
                    this.textReplacer.updateRules(this.getCurrentRules());
                    
                    // 如果开启了实时处理，重新处理文本
                    if (this.realTimeProcessing && this.mainEditor.value.trim()) {
                        this.processText();
                    }
                }
            }

            // 编辑小组
            editGroup(groupId) {
                const group = this.groupManager.getGroupById(groupId);
                if (group) {
                    this.groupNameInput.value = group.name;
                    this.renderReplacementRules();
                }
            }

            // 删除小组
            deleteGroup(groupId) {
                if (this.groupManager.deleteGroup(groupId)) {
                    this.renderGroupList();
                    this.renderReplacementRules();
                    this.updateCurrentGroupDisplay();
                    
                    // 更新替换器规则
                    this.textReplacer.updateRules(this.getCurrentRules());
                }
            }

            // 渲染当前小组的替换规则
            renderReplacementRules() {
                this.replacementRulesContainer.innerHTML = '';
                
                // 获取当前小组的替换规则
                const currentGroup = this.groupManager.getCurrentGroup();
                const rules = currentGroup ? currentGroup.rules : {};
                
                // 为每个规则创建输入框
                Object.keys(rules).forEach((keyword, index) => {
                    this.addRuleInput(keyword, rules[keyword], index);
                });
                
                // 如果没有规则，添加一个空规则
                if (Object.keys(rules).length === 0) {
                    this.addRuleInput();
                }
            }

            // 添加规则输入框
            addRuleInput(keyword = '', replacement = '', index = null) {
                const ruleIndex = index !== null ? index : this.replacementRulesContainer.children.length;
                const ruleItem = document.createElement('div');
                ruleItem.className = 'rule-item';
                ruleItem.dataset.index = ruleIndex;
                
                ruleItem.innerHTML = `
                    <input type="text" class="rule-input keyword-input" placeholder="敏感词" value="${this.escapeHtml(keyword)}">
                    <span style="font-size: 16px;">→</span>
                    <input type="text" class="rule-input replacement-input" placeholder="替换为" value="${this.escapeHtml(replacement)}">
                    <button class="remove-rule-btn" data-index="${ruleIndex}">×</button>
                `;
                
                this.replacementRulesContainer.appendChild(ruleItem);
                
                // 绑定删除按钮事件
                const removeBtn = ruleItem.querySelector('.remove-rule-btn');
                removeBtn.addEventListener('click', (e) => {
                    const index = e.target.dataset.index;
                    this.removeRule(index);
                });
            }

            // 从输入框收集规则
            collectRulesFromInputs() {
                const newRules = {};
                const ruleItems = this.replacementRulesContainer.querySelectorAll('.rule-item');
                
                ruleItems.forEach(item => {
                    const keyword = item.querySelector('.keyword-input').value.trim();
                    const replacement = item.querySelector('.replacement-input').value;
                    
                    if (keyword) {
                        newRules[keyword] = replacement;
                    }
                });
                
                return newRules;
            }

            // 删除规则
            removeRule(index) {
                const ruleItems = this.replacementRulesContainer.querySelectorAll('.rule-item');
                if (index >= 0 && index < ruleItems.length) {
                    ruleItems[index].remove();
                    // 重新编号
                    this.updateRuleIndices();
                    
                    // 如果没有规则了，添加一个空规则
                    if (this.replacementRulesContainer.children.length === 0) {
                        this.addRuleInput();
                    }
                }
            }

            // 更新规则索引
            updateRuleIndices() {
                const ruleItems = this.replacementRulesContainer.querySelectorAll('.rule-item');
                ruleItems.forEach((item, index) => {
                    item.dataset.index = index;
                    item.querySelector('.remove-rule-btn').dataset.index = index;
                });
            }

            // 保存当前小组
            saveCurrentGroup() {
                const groupName = this.groupNameInput.value.trim();
                if (!groupName) {
                    alert('请输入小组名称');
                    return false;
                }
                
                // 检查是否与其他小组重名
                const currentGroup = this.groupManager.getCurrentGroup();
                const groups = this.groupManager.getAllGroups();
                const nameExists = groups.some(group => 
                    group.id !== currentGroup.id && 
                    group.name.toLowerCase() === groupName.toLowerCase()
                );
                
                if (nameExists) {
                    alert('已存在同名小组，请使用其他名称');
                    return false;
                }
                
                const rules = this.collectRulesFromInputs();
                
                if (currentGroup) {
                    // 更新现有小组
                    this.groupManager.updateGroup(currentGroup.id, {
                        name: groupName,
                        rules: rules
                    });
                } else {
                    // 创建新小组
                    const newGroupId = this.groupManager.addGroup(groupName, rules);
                    if (newGroupId) {
                        this.groupManager.switchGroup(newGroupId);
                    }
                }
                
                this.renderGroupList();
                this.updateCurrentGroupDisplay();
                
                // 更新替换器规则
                this.textReplacer.updateRules(this.getCurrentRules());
                
                return true;
            }

            // 新建小组
            createNewGroup() {
                // 清空表单
                this.groupNameInput.value = '';
                this.replacementRulesContainer.innerHTML = '';
                this.addRuleInput();
                this.groupNameInput.focus();
                
                // 确保新创建的小组能被正确渲染
            }

            // 导入小组 - 支持JSON和TXT格式
            importGroup(file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        // 获取文件类型
                        const fileName = file.name.toLowerCase();
                        let fileType = 'json';
                        if (fileName.endsWith('.txt')) {
                            fileType = 'txt';
                        } else if (!fileName.endsWith('.json')) {
                            throw new Error('不支持的文件格式，仅支持JSON和TXT');
                        }
                        
                        const fileData = e.target.result;
                        const newGroupId = this.groupManager.importGroup(fileData, fileType);
                        
                        if (newGroupId) {
                            this.renderGroupList();
                            this.groupManager.switchGroup(newGroupId);
                            this.renderGroupList();
                            this.renderReplacementRules();
                            this.updateCurrentGroupDisplay();
                            
                            // 更新替换器规则
                            this.textReplacer.updateRules(this.getCurrentRules());
                            
                            alert('小组导入成功');
                        } else {
                            alert('导入失败，文件格式不正确');
                        }
                    } catch (error) {
                        console.error('导入小组失败:', error);
                        alert('导入失败: ' + error.message);
                    }
                };
                reader.readAsText(file);
            }

            // 导出当前小组 - 默认导出为JSON，也支持TXT
            exportCurrentGroup() {
                try {
                    const group = this.groupManager.getCurrentGroup();
                    if (!group) {
                        alert('未找到当前小组数据');
                        return;
                    }
                    
                    // 询问导出格式
                    const format = confirm('是否导出为TXT格式？\n(取消将导出为JSON格式)');
                    const exportFormat = format ? 'txt' : 'json';
                    
                    const exportData = this.groupManager.exportCurrentGroup(exportFormat);
                    if (!exportData) {
                        alert('导出失败，无法获取小组数据');
                        return;
                    }
                    
                    let content, mimeType, extension;
                    
                    if (exportFormat === 'txt') {
                        content = exportData;
                        mimeType = 'text/plain';
                        extension = 'txt';
                    } else {
                        content = JSON.stringify(exportData, null, 2);
                        mimeType = 'application/json';
                        extension = 'json';
                    }
                    
                    const blob = new Blob([content], { type: mimeType });
                    const url = URL.createObjectURL(blob);
                    
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${group.name}_敏感词小组.${extension}`;
                    document.body.appendChild(a);
                    a.click();
                    
                    // 清理
                    setTimeout(() => {
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                    }, 0);
                } catch (error) {
                    console.error('导出小组失败:', error);
                    alert('导出失败: ' + error.message);
                }
            }

            // 绑定事件
            bindEvents() {
                // 处理文本按钮
                document.getElementById('processBtn').addEventListener('click', () => this.processText());

                // 查看历史记录按钮
                document.getElementById('showMainHistoryBtn').addEventListener('click', () => {
                    this.mainHistory.renderHistoryList(this.mainHistoryList);
                    // 滚动到历史记录区域
                    this.mainHistoryList.scrollIntoView({ behavior: 'smooth' });
                });

                document.getElementById('showSecondaryHistoryBtn').addEventListener('click', () => {
                    this.secondaryHistory.renderHistoryList(this.secondaryHistoryList);
                    // 滚动到历史记录区域
                    this.secondaryHistoryList.scrollIntoView({ behavior: 'smooth' });
                });

                // 清空历史记录按钮
                document.getElementById('clearMainHistoryBtn').addEventListener('click', () => {
                    if (confirm('确定要清空主编辑区的所有历史记录吗？')) {
                        this.mainHistory.clearRecords();
                        this.mainHistory.renderHistoryList(this.mainHistoryList);
                        this.mainHistory.updateHistoryStatus(this.mainHistoryStatus);
                    }
                });

                document.getElementById('clearSecondaryHistoryBtn').addEventListener('click', () => {
                    if (confirm('确定要清空二次编辑区的所有历史记录吗？')) {
                        this.secondaryHistory.clearRecords();
                        this.secondaryHistory.renderHistoryList(this.secondaryHistoryList);
                        this.secondaryHistory.updateHistoryStatus(this.secondaryHistoryStatus);
                    }
                });

                // 复制按钮
                document.getElementById('copyBtn').addEventListener('click', () => {
                    const text = this.secondaryEditor.value;
                    if (text) {
                        navigator.clipboard.writeText(text).then(() => {
                            alert('内容已复制到剪贴板');
                        }).catch(err => {
                            console.error('复制失败:', err);
                            alert('复制失败，请手动复制');
                        });
                    } else {
                        alert('没有可复制的内容');
                    }
                });

                // 添加替换规则按钮
                document.getElementById('addRuleBtn').addEventListener('click', () => {
                    this.addRuleInput();
                });

                // 敏感词小组管理按钮
                document.getElementById('groupsBtn').addEventListener('click', () => {
                    const currentGroup = this.groupManager.getCurrentGroup();
                    if (currentGroup) {
                        this.groupNameInput.value = currentGroup.name;
                    }
                    this.renderReplacementRules();
                    document.getElementById('groupsModal').classList.add('show');
                });

                // 保存当前小组
                document.getElementById('saveGroupBtn').addEventListener('click', () => {
                    if (this.saveCurrentGroup()) {
                        alert('小组保存成功');
                    }
                });

                // 新建小组
                document.getElementById('addNewGroupBtn').addEventListener('click', () => {
                    this.createNewGroup();
                });

                // 导入小组
                document.getElementById('importGroupBtn').addEventListener('click', () => {
                    document.getElementById('groupFileInput').click();
                });

                document.getElementById('groupFileInput').addEventListener('change', (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        this.importGroup(file);
                    }
                    // 重置输入，允许重复选择同一文件
                    e.target.value = '';
                });

                // 导出当前小组
                document.getElementById('exportGroupBtn').addEventListener('click', () => {
                    this.exportCurrentGroup();
                });

                // 导入导出文本按钮
                document.getElementById('importBtn').addEventListener('click', () => {
                    document.getElementById('fileInput').click();
                });

                document.getElementById('fileInput').addEventListener('change', (e) => {
                    this.importText(e);
                });

                document.getElementById('exportBtn').addEventListener('click', () => {
                    this.exportText();
                });

                // 加载示例按钮
                document.getElementById('loadSampleBtn').addEventListener('click', () => {
                    this.loadSampleText();
                });

                // 清空所有按钮
                document.getElementById('clearAllBtn').addEventListener('click', () => {
                    if (confirm('确定要清空所有内容和历史记录吗？')) {
                        this.mainEditor.value = '';
                        this.secondaryEditor.value = '';
                        this.mainHistory.clearRecords();
                        this.secondaryHistory.clearRecords();
                        this.mainHistory.renderHistoryList(this.mainHistoryList);
                        this.secondaryHistory.renderHistoryList(this.secondaryHistoryList);
                        this.mainHistory.updateStats(this.mainStats);
                        this.secondaryHistory.updateStats(this.secondaryStats);
                        this.mainHistory.updateHistoryStatus(this.mainHistoryStatus);
                        this.secondaryHistory.updateHistoryStatus(this.secondaryHistoryStatus);
                    }
                });

                // 实时处理切换
                this.realTimeToggle.addEventListener('change', (e) => {
                    this.realTimeProcessing = e.target.checked;
                    
                    // 如果开启了实时处理，立即处理一次
                    if (this.realTimeProcessing && this.mainEditor.value.trim()) {
                        this.processText();
                    }
                });

                // 主编辑器输入事件（用于实时处理）
                this.mainEditor.addEventListener('input', () => {
                    if (this.realTimeProcessing) {
                        clearTimeout(this.processingTimeout);
                        this.processingTimeout = setTimeout(() => {
                            this.processText();
                        }, 500); // 延迟500ms处理，避免频繁处理
                    }
                });

                // 模态框事件
                document.getElementById('modalClose').addEventListener('click', () => {
                    document.getElementById('historyModal').classList.remove('show');
                });

                document.getElementById('modalCancelBtn').addEventListener('click', () => {
                    document.getElementById('historyModal').classList.remove('show');
                });

                document.getElementById('groupsClose').addEventListener('click', () => {
                    document.getElementById('groupsModal').classList.remove('show');
                });

                document.getElementById('groupsCancelBtn').addEventListener('click', () => {
                    document.getElementById('groupsModal').classList.remove('show');
                });

                document.getElementById('restoreBtn').addEventListener('click', () => {
                    const recordId = document.getElementById('restoreBtn').dataset.recordId;
                    const editorType = document.getElementById('restoreBtn').dataset.editorType;
                    
                    if (editorType === 'main') {
                        if (this.mainHistory.restoreRecord(recordId)) {
                            this.mainHistory.renderHistoryList(this.mainHistoryList);
                            this.mainHistory.updateHistoryStatus(this.mainHistoryStatus);
                            
                            // 如果开启了实时处理，重新处理
                            if (this.realTimeProcessing) {
                                this.processText();
                            }
                        }
                    } else {
                        if (this.secondaryHistory.restoreRecord(recordId)) {
                            this.secondaryHistory.renderHistoryList(this.secondaryHistoryList);
                            this.secondaryHistory.updateHistoryStatus(this.secondaryHistoryStatus);
                        }
                    }
                    
                    document.getElementById('historyModal').classList.remove('show');
                });

                // 点击模态框外部关闭
                window.addEventListener('click', (e) => {
                    if (e.target === document.getElementById('historyModal')) {
                        document.getElementById('historyModal').classList.remove('show');
                    }
                    if (e.target === document.getElementById('groupsModal')) {
                        document.getElementById('groupsModal').classList.remove('show');
                    }
                });

                // 主题切换
                document.getElementById('themeToggle').addEventListener('click', () => {
                    this.toggleTheme();
                });
            }

            // 处理文本 - 应用敏感词替换规则
            processText() {
                const text = this.mainEditor.value;
                if (!text.trim()) {
                    this.secondaryEditor.value = '';
                    this.secondaryHistory.debouncedSave();
                    this.secondaryHistory.updateStats(this.secondaryStats);
                    return;
                }

                // 使用文本替换器处理文本，应用当前小组的规则
                const replacer = new TextReplacer(text, this.getCurrentRules());
                const processed = replacer.process();

                // 将处理结果放入二次编辑区
                this.secondaryEditor.value = processed;
                
                // 触发保存
                this.secondaryHistory.debouncedSave();
                this.secondaryHistory.updateStats(this.secondaryStats);
                this.secondaryHistory.renderHistoryList(this.secondaryHistoryList);
                this.secondaryHistory.updateHistoryStatus(this.secondaryHistoryStatus);
            }

            // 导入文本
            importText(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.mainEditor.value = e.target.result;
                    this.mainHistory.debouncedSave();
                    this.mainHistory.updateStats(this.mainStats);
                    
                    // 如果开启了实时处理，处理文本
                    if (this.realTimeProcessing) {
                        this.processText();
                    }
                };
                reader.readAsText(file);
                
                // 重置输入，允许重复选择同一文件
                event.target.value = '';
            }

            // 导出文本
            exportText() {
                const text = this.secondaryEditor.value;
                if (!text.trim()) {
                    alert('没有可导出的内容');
                    return;
                }
                
                const blob = new Blob([text], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = '处理后的文本_' + new Date().toLocaleString().replace(/[/: ]/g, '-') + '.txt';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }

            // 加载示例文本
            loadSampleText() {
                const sampleText = `这是一段包含敏感词、百分比和小数的示例文本：
- 涉及疾病的词汇：胃病、癌症、炎症
- 涉及不当言论：滚出去、妈的
- 涉及数字：123人、99%的概率、11.22元、3.1415、.67、-.89、2024年、第3名、-5.67`;
                
                this.mainEditor.value = sampleText;
                this.mainHistory.debouncedSave();
                this.mainHistory.updateStats(this.mainStats);
                
                // 处理文本
                this.processText();
            }

            // 切换主题
            toggleTheme() {
                const body = document.body;
                const isDarkMode = body.classList.toggle('dark-mode');
                const themeIcon = document.querySelector('#themeToggle i');
                
                if (isDarkMode) {
                    themeIcon.classList.remove('fa-moon-o');
                    themeIcon.classList.add('fa-sun-o');
                    localStorage.setItem('darkMode', 'true');
                } else {
                    themeIcon.classList.remove('fa-sun-o');
                    themeIcon.classList.add('fa-moon-o');
                    localStorage.setItem('darkMode', 'false');
                }
            }

            // 检查主题设置
            checkTheme() {
                const isDarkMode = localStorage.getItem('darkMode') === 'true';
                const themeIcon = document.querySelector('#themeToggle i');
                
                if (isDarkMode) {
                    document.body.classList.add('dark-mode');
                    themeIcon.classList.remove('fa-moon-o');
                    themeIcon.classList.add('fa-sun-o');
                } else {
                    themeIcon.classList.remove('fa-sun-o');
                    themeIcon.classList.add('fa-moon-o');
                }
            }

            // HTML转义
            escapeHtml(unsafe) {
                if (!unsafe) return '';
                return unsafe
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            }
        }

        // 页面加载完成后初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            try {
                const app = new TextProcessor();
                
                // 首次使用说明弹窗控制
                const guideModal = document.getElementById('guideModal');
                const guideClose = document.getElementById('guideClose');
                const guideConfirmBtn = document.getElementById('guideConfirmBtn');
                const dontShowAgain = document.getElementById('dontShowAgain');

                // 检查是否需要显示引导（首次进入或未勾选“不再显示”）
                const hasShownGuide = localStorage.getItem('hasShownGuide') === 'true';
                if (!hasShownGuide) {
                    setTimeout(() => {
                        guideModal.classList.add('show');
                    }, 500); // 延迟0.5秒显示，避免与页面加载冲突
                }

                // 关闭弹窗（右上角X）
                guideClose.addEventListener('click', () => {
                    guideModal.classList.remove('show');
                    if (dontShowAgain.checked) {
                        localStorage.setItem('hasShownGuide', 'true');
                    }
                });

                // 确认按钮（我知道了）
                guideConfirmBtn.addEventListener('click', () => {
                    guideModal.classList.remove('show');
                    if (dontShowAgain.checked) {
                        localStorage.setItem('hasShownGuide', 'true');
                    }
                });

                // 点击弹窗外部关闭
                window.addEventListener('click', (e) => {
                    if (e.target === guideModal) {
                        guideModal.classList.remove('show');
                        if (dontShowAgain.checked) {
                            localStorage.setItem('hasShownGuide', 'true');
                        }
                    }
                });
            } catch (error) {
                console.error('应用初始化失败:', error);
                alert('应用加载失败: ' + error.message);
            }
        });
    </script>
</body>
</html>
    